import axios from 'axios'
import qs from 'querystring'
import {
  Message,
  Loading
} from 'element-ui'

let loading;

function startLoading() {
  loading = Loading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(255,255,255,0.4)'
  })
}

function endLoading() {
  loading.close()
}
let needLoadingRequestCount = 0;

function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
axios.defaults.timeout = 10000;

axios.interceptors.request.use(config => {
  if (config.method === 'post' && config.data.constructor !== FormData) {
    config.data = qs.stringify(config.data)
  }
  if (config.url == 'login') {
    showFullScreenLoading()
  }
  return config;
}, error => {
  Message.error('错误的传参')
  return Promise.reject(error);
});

axios.interceptors.response.use((res) => {
  tryHideFullScreenLoading()
  return res
}, (error) => {
  // Message.warning('正在加载!');
  console.log('网络异常')
  return Promise.reject(error)
})


export function fetchPost(url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params).then(Response => {
      resolve(Response.data)
    }, err => {
      reject(err)
    }).catch(error => {
      reject(error)
    })
  })
}

export function fetchPostToken(url, params) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: url,
      headers: {
        'Authorization': sessionStorage.getItem('token')
      },
      data: params
    }).then(response => {
      resolve(response.data)
    }).catch(error => {
      reject(error)
    })
  })
}

export function fetchGetToken(url, param) {
  return new Promise((resolve, reject) => {
    axios(url, {
      params: param,
      headers: {
        'Authorization': sessionStorage.getItem('token')
      }
    }).then(response => {
      resolve(response.data)
    }).catch(error => {
      reject(error)
    })
  })
}

export function fetchPutToken(url,param){
  return new Promise((resolve,reject)=>{
    axios({
      method:'put',
      url:url,
      headers: {
        'Authorization': sessionStorage.getItem('token')
      },
      data: param
    }).then(res => {
      resolve(res.data)
    })
    .catch(err => {
      reject(err); 
    })
  })
}

export function fetchDeleteToken(url,param){
  return new Promise((resolve,reject)=>{
    axios({
      method:'delete',
      url:url,
      headers: {
        'Authorization': sessionStorage.getItem('token')
      },
      data: param
    }).then(res => {
      resolve(res.data)
    })
    .catch(err => {
      reject(err); 
    })
  })
}